import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import {message, Modal} from "ant-design-vue";
import store from '../store'

/**
 * 指定长度和进制的UUID
 * @param len       长度
 * @param radix     进制
 * @returns {string}
 */
function uuid(len, radix) {
    let chars = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
    let uuid = [], i;
    radix = radix || chars.length;
    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        let r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}


const pageUrl = process.env.VUE_APP_BASEURL;

const service = axios.create({
    baseURL: pageUrl
});
NProgress.configure({
    showSpinner: false
});


service.interceptors.request.use(request => {
    // 请求带token
    request.headers['token'] = window.localStorage.getItem('access_token')

    NProgress.start(); // start progress bar

    return request;
}, error => {
    return Promise.reject(error);
});

service.interceptors.response.use(response => {
        NProgress.done();
        let outObj = response.data;
        if(outObj.code && outObj.code != 200){
            message.warn(outObj.msg);
            return response;
        }
        // if (outObj.hasOwnProperty("flag")) {
        if (Object.prototype.hasOwnProperty.call(outObj, "rtnCode")) {
            if (outObj.rtnCode !== "0000000") {
                let ignoreErrorCodeList = store.state.ErrorCode.ignoreErrorCode
                if(ignoreErrorCodeList.findIndex( e => e === outObj.rtnCode) === -1){
                    store.commit('ErrorCode/setErrorCodeVisible', true)
                    store.commit('ErrorCode/setErrorCodeForm', outObj)
                }
            }
        }

        return response;
    }, err => {
        NProgress.done();
        if (err.response.status){
                localStorage.removeItem('access_token');
                localStorage.removeItem('userIdMes');
                localStorage.removeItem('permissionList');
                message.warn('登录过期，请重新登录');
                window.location.href = "/";
              return
        }
    }
);

export default service;
